package org.andolphin.client;

import org.andolphin.client.Andolphin.Prefs;
import org.andolphin.client.model.User;
import org.andolphin.client.utils.RemoteAccess;
import org.andolphin.client.utils.StringUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {
    private Button loginBtn;
    private Button cancelBtn;
    private Button registerBtn;
    private EditText usernameEdit;
    private EditText passwordEdit;
    private String errorMessage;

    private static final int DIALOG_ERROR_INPUT = 0;

    private static final int DIALOG_PROGRESS = 1;

    public static final int RESULT_USER_NOT_EXISTS = -3;

    public static final int RESULT_PASSWORD_ERROR = -4;

    private final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            Result result;
            dismissDialog(DIALOG_PROGRESS);
            switch (msg.what) {
            case Result.CODE_NET_ERROR:
                errorMessage = getResources().getString(R.string.msg_net_error);
                showDialog(DIALOG_ERROR_INPUT);
                break;
            case Result.CODE_SUCCESS:
                loginSuccess(msg);
                break;
            case RESULT_USER_NOT_EXISTS:
                errorMessage = getResources().getString(R.string.msg_user_not_exists);
                showDialog(DIALOG_ERROR_INPUT);
                break;
            case RESULT_PASSWORD_ERROR:
                errorMessage = getResources().getString(R.string.msg_password_error);
                showDialog(DIALOG_ERROR_INPUT);
                break;
            case Result.CODE_INPUT_ERROR:
                result = (Result) msg.getData().getSerializable(Result.KEY);
                errorMessage = StringUtils.join(result.getErrorMessages(), "\n");
                showDialog(DIALOG_ERROR_INPUT);
                break;
            default:
                result = (Result) msg.getData().getSerializable(Result.KEY);
                errorMessage = result.getMessage();
                showDialog(DIALOG_ERROR_INPUT);
                break;
            }
        }

    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        usernameEdit = (EditText) findViewById(R.id.edit_login_username);
        passwordEdit = (EditText) findViewById(R.id.edit_login_passowrd);

        SharedPreferences prefs = getSharedPreferences(Andolphin.Prefs.ANDOLPHIN, Prefs.MODE);
        usernameEdit.setText(prefs.getString(Andolphin.Prefs.USERNAME, ""));
        passwordEdit.setText(prefs.getString(Andolphin.Prefs.PASSWORD, ""));

        loginBtn = (Button) findViewById(R.id.btn_login_ok);
        loginBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (validateInput()) {
                    doLogin();
                }

            }
        });

        cancelBtn = (Button) findViewById(R.id.btn_login_cancel);
        cancelBtn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                LoginActivity.this.finish();
            }
        });

        registerBtn = (Button) findViewById(R.id.btn_login_register);
        registerBtn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Intent intent = new Intent(Andolphin.Intent.REGISTER);
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                startActivity(intent);
            }
        });
    }

    protected void doLogin() {
        showDialog(DIALOG_PROGRESS);
        final ResultHandler rh = ResultHandler.create(handler, this);
        new Thread(new Runnable() {

            public void run() {
                RemoteAccess.login(usernameEdit.getText().toString(), passwordEdit.getText().toString(), rh);
            }
        }).start();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        Dialog dialog = null;
        switch (id) {
        case DIALOG_ERROR_INPUT:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getResources().getString(R.string.input_error));
            builder.setMessage("");
            builder.setCancelable(false).setPositiveButton(getResources().getString(R.string.ok),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });

            builder.setIcon(getResources().getDrawable(R.drawable.exclamation));
            dialog = builder.create();
            break;
        case DIALOG_PROGRESS:
            ProgressDialog progressDialog;
            progressDialog = new ProgressDialog(this);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setMessage(getResources().getString(R.string.msg_loading));
            progressDialog.setCancelable(false);
            dialog = progressDialog;
            break;
        default:
            dialog = super.onCreateDialog(id);
            break;
        }
        return dialog;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
        case DIALOG_ERROR_INPUT:
            ((AlertDialog) dialog).setMessage(this.errorMessage);
            break;
        default:
            super.onPrepareDialog(id, dialog);
            break;
        }

    }

    protected boolean validateInput() {
        boolean result = true;
        if (StringUtils.isEmpty(usernameEdit.getText().toString())) {
            result = false;
            errorMessage = getResources().getString(R.string.msg_username_invalid);
            showDialog(DIALOG_ERROR_INPUT);
        } else if (StringUtils.isEmpty(passwordEdit.getText().toString())) {
            result = false;
            errorMessage = getResources().getString(R.string.msg_password_invalid);
            showDialog(DIALOG_ERROR_INPUT);
        } else {
            result = true;
        }
        return result;
    }

    protected void loginSuccess(Message msg) {
        Result result = (Result) msg.getData().getSerializable(Result.KEY);
        User user = new User();
        user.fromJSON(result.getData().getRawData());
        SharedPreferences prefs = getSharedPreferences(Andolphin.Prefs.ANDOLPHIN, Prefs.MODE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(Andolphin.Prefs.USERNAME, user.getUsername());
        editor.putString(Andolphin.Prefs.PASSWORD, user.getPassword());
        editor.putString(Andolphin.Prefs.EMAIL, user.getEmail());
        editor.putString(Andolphin.Prefs.AUTH_TOKEN, user.getAuthToken());
        editor.putLong(Andolphin.Prefs.EXPIRE, user.getExpired().getTime());
        editor.commit();
        finish();
        Toast.makeText(this, getResources().getString(R.string.msg_login_success), Toast.LENGTH_SHORT).show();
    }

}
